/**
 * 登录跳转逻辑,参数处理
 * @author:ml
 * 
 * */
var serverHost = "http://120.79.227.110";// 注意:更改login.js 
var refresh = null;//刷新方法
var initItem = null;//初始化页面样式方法
var refresHeight = "20px";
var closeSingleWebViews = null;
//阻止只有一个webview时返回为空白页的情况
var oldback = mui.back;
mui.back = function(){
	try{
		var all = plus.webview.all();
		if(all.length==1){
			router.href("index.html");
			return false;	
		}
	}catch(e){}
	oldback();
	return true;
}


try{
	$(document).ready(function () {
		bind();
		headimgd();

	});
	function headimgd(){
		$("#headimgb").attr('src',serverHost+"/mobile/img/banner.png?r="+Math.random());
		$("#banner2").attr('src',serverHost+"/mobile/img/banner2.png?r="+Math.random());
	}
	if(window.plus){
		closeWaiting();
	}
	function closeWaiting(){
		plus.nativeUI.closeWaiting();
		setInterval(function(){
			try{
				plus.nativeUI.closeWaiting();
			}catch(e){}
		}, 1000);
	}
	
	document.addEventListener('plusready',closeWaiting);
	window.addEventListener('refresh',function(event){
		if(event.detail.comurl=="index"){
			return;
		}
		router.dealParam({
			sel:event.detail.sel||null,
		   	navsel:event.detail.navsel||null,
		   	datesel:event.detail.datesel||null
		   
		});
		param.psid = event.detail.psid||param.psid;
		psid = param.psid;
		if(event.detail.eqid)param.eqid = event.detail.eqid||param.eqid;
/*		console.log(plus.webview.currentWebview().id);
		console.log(param.eqid);*/
		//alert(window.refresh);
		if(refresh)refresh();
		if(initItem)initItem();
		
		if(window.notice)setTimeout(notice,1);
		if(window.noticename)setTimeout(noticename,1);
	});
}catch(e){
}
(function($){
	try{
		endPullRefresh = function (id){
			try{
				setTimeout(function(){
					//mui(id).pullRefresh().endPulldown();
					mui(id).pullRefresh().endPulldownToRefresh();
				}, 500);
			}catch(e){}
		}
	var isAlertLoginRefresh = false;
	param = {};//所有传递的参数
	$.proAjax = function (opt){

		
		$.ajax({
			type: "POST",
			url: serverHost + "/mobile/loginstate",
			data: { LOGIN_USER: param.LOGIN_USER, logpassword: localStorage.getItem('logpassword') },
			dataType: 'json',
			success: function (data) {
				if (data.errorMsg && !isAlertLoginRefresh) {
					isAlertLoginRefresh = true;
					mui.alert(data.errorMsg,'',function(){
						logSrv.logout();
						isAlertLoginRefresh = false;
					});
					
				} else if(!data.errorMsg){
					delete data.logpassword;
					localStorage.setItem('data',JSON.stringify(data));
					router.dealParam(data);
					delete param.islog;
					
					
					opt.type = "POST";
					opt.dataType = "json";
					opt.url = serverHost + opt.url;
					var parms = {};
					var success = opt.success;
					opt.success = function(data){
						success(data);
					}
					for(var key in param){
						parms[key] = param[key];
					}
					if (opt.data) {
						for (var key in opt.data) {
							parms[key] = opt.data[key];
						}
					}
					
					opt.data = parms;
					opt.error = function(a,status){ 
						//alert(status);
					};
					$.ajax(opt);
				}
			}
		})
	}
	
	$param = function(otherParam){
		var paramArr = $("form").serializeArray();
		var parms = {};
		$.each(paramArr,function(){
			parms[this.name] = this.value;
		});
		
		if(otherParam){
			var key;
			for(key in otherParam){
				parms[key] = otherParam[key];
			}
		}
		return parms;
	}
	num2OfEmpty = function (value){
		if(!value && value != 0){
			return "-";
		}else{
			return (+value).toFixed(2);
		}
	}
	dateOfEmpty = function (value){
		if(!value && value != 0){
			return "-";
		}else{
			return new Date(value).format("yyyy年MM月dd日 hh时mm分");
		}
	}
	//通用js 生成 html 并带格式化
	window.AjaxHandler = function(){
		// 需要格式的方法写入元素中，前端id和后台put的key要一致,模板元素要为display：none
		//数组数据添加到列表
		this.arrayAddToHtml = function (modelId,data,others,fun){
			$("#"+modelId).parent().find(".norecord").remove();
			if(!data || !modelId ) {
				return;
			}
			if(data.length==0){$("#"+modelId).after("<span class='norecord'>无记录</span>");}
			$("*[data-list='"+modelId+"']").remove();
			var prevd = $("#"+modelId)
			var model = $("#"+modelId).clone();
			model.removeAttr("id");
			model.show();
			var otherElm = [];
			if(others){
				if($.isArray(others)){
					$.each(others,function(){
						var elm = $("#"+this).clone();
						elm.show();
						elm.attr("data-list",modelId);
						otherElm.push(elm);
					})
				}else{
					var elm = $("#"+others).clone();
					elm.show();
					elm.attr("data-list",modelId);
					otherElm.push(elm);
				}
			}
			var lastElm = null;
			$.each(data,function(){
				var cloned = model.clone();
				cloned.attr("data-list",modelId);
				
				var key;
				for(key in this){
					var fmtFun = cloned.find("#"+key).attr("data-fmtFun");//格式化方法
					if(fmtFun){
						cloned.find("#"+key).html(eval(fmtFun+"("+this[key]+")"));
					}else{
						cloned.find("#"+key).html(this[key]);
					}
				}
				fun && fun.call(this,cloned,this);
				if(lastElm){
					lastElm.after(cloned);
					lastElm = cloned;
				}else{
					prevd.after(cloned);
					lastElm = cloned;
				}
				$.each(otherElm,function(){
					if(lastElm){
						var temp = this.clone();
						lastElm.after(temp);
						lastElm = temp;
					}else{
						lastElm = this.clone();
						prevd.after(lastElm);
					}
				});
			});
		}
		
	}
	}catch(e){
	}
}(window.jQuery));


(function ($) {
	try{
	AppContext = {
			
	/**
	 * 所有跳转使用这个Router对象实现
	 * 
	 * */
	Router: function () {
		this.clear = function () {
			param = {};
		}
		//每次跳转首先处理并存储接收传过来的参数
		this.dealParam = function (others) {
			var search = location.search;
			if (search) {
				search = search.replace("?", "");
				$.each(search.split("&"), function () {
					var sers = this.split("=");
					if (sers.length > 1) {
						if (sers[0] == "psids") {
							var user_psids = decodeURIComponent(sers[1]).split(",");
							param.psids = user_psids + '';
						} else {
							param[sers[0]] = decodeURIComponent(sers[1]);
						}
					}
				});
			}
			if(others){
				for(var key in others ){
					param[key] = others[key]+"";
				}
			}
		}
		this.open = function(url, data){
			if (data) {
				for (var key in data) {
					param[key] = data[key];
				}
			}
			var urlparam = {}; 
			if (url.indexOf("?") > -1) {
				var search = url.split("?")[1];
				url = url.split("?")[0];
				if (search) {
					$.each(search.split("&"), function () {
						var sers = this.split("=");
						if (sers.length > 1) {
							if (sers[0] == "psids") {
								var user_psids = decodeURIComponent(sers[1]).split(",");
								param.psids = user_psids + '';
							} else {
								param[sers[0]] = decodeURIComponent(sers[1]);
							}
						}
					});
				}
			}
				console.log(1);
			location.href = url + "?" + $.param(param);
		}
		this.href = function (url, data,newd) {
			
			var oldurl = url;
			if (data) {
				for (var key in data) {
					param[key] = data[key];
				}
			}
			var urlparam = {}; 
			if (url.indexOf("?") > -1) {
				var search = url.split("?")[1];
				url = url.split("?")[0];
				if (search) {
					$.each(search.split("&"), function () {
						var sers = this.split("=");
						if (sers.length > 1) {
							if (sers[0] == "psids") {
								var user_psids = decodeURIComponent(sers[1]).split(",");
								param.psids = user_psids + '';
							} else {
								param[sers[0]] = decodeURIComponent(sers[1]);
							}
						}
					});
				}
			}
			var urlid = url.split("/").pop().split(".")[0];
			var creats = false;
			if(closeSingleWebViews && !$.inArray(urlid,"index","myInfor")){
				creats = closeSingleWebViews();
			};
			 
			try{
				var  detailPage = plus.webview.getWebviewById(urlid);
				if(urlid!="index" && urlid!="monitor")mui.fire(detailPage,'refresh',param);
			}catch(e){}
			localStorage.setItem("data",JSON.stringify(param));
			mui.openWindow({
			   url: url,
			   id: urlid,
			   createNew: creats,
			   extras:{
			   	sel:param.sel,
			   	navsel:param.navsel,
			   	datesel:param.datesel,
			   	comurl:urlid,
			   	psid:param.psid
			   },
			   show: {
				   	autoShow:true,
			      	aniShow:'none',
			   },
			   waiting: {
			   	autoShow: true
			   }
			});
			
		}
		
	},
	}
	window.router = new AppContext.Router();

	var paramdata = localStorage.getItem('data');
	paramdata && router.dealParam(JSON.parse(paramdata));
	
	logSrv = {
			// 登录
			login: function () {
				var username = $("#username").val();
				var password = $("#password").val();
				$.ajax({
					type: "POST",
					url: serverHost + "/mobile/login",
					data: { username: username, password: password },
					dataType: 'json',
					success: function (data) {
						if (data.errorMsg) {
							alert(data.errorMsg);
						} else {
							localStorage.setItem('username',username);
							localStorage.setItem('password',password);
							router.dealParam(data);
							router.href("./index.html");
						}
					},
					error:function(){
						alert("登录失败!");
					}
				})
			},
			// 退出
			logout: function () {
				localStorage.setItem("data","");
				localStorage.clear();
				param = {};
				mui.openWindow({
				   url: "login.html",
				   id:'login',
				   createNew: true,
				   show: {
					   	autoShow:true,
				      	aniShow:'none',
				   },
				   waiting: {
				   	autoShow: false
				   }
				})
			}
	}


	
	Date.prototype.format = function (fmt) { //author: meizz 
	    var o = {
	        "M+": this.getMonth() + 1, //月份 
	        "d+": this.getDate(), //日 
	        "h+": this.getHours(), //小时 
	        "m+": this.getMinutes(), //分 
	        "s+": this.getSeconds(), //秒 
	        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
	        "S": this.getMilliseconds() //毫秒 
	    };
	    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	    for (var k in o)
	    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	    return fmt;
	}
	//检查登录状态
	//if($.isEmptyObject(param) && $("#username").length==0)logSrv.logout();
	
	}catch(e){
	}
}(window.jQuery));
function bind(){
	try{
	//阻止a标签点击行为，转为调用router的方法
	var unbind = '.mui-action-back, mui-table-view-cell>a[href="index.html"] ,a[href="#tab-KGG"],a[href="#tab-XB"],a[href="#tab-NBQ"],a[href="#tab-QXY"], .mui-control-item, .mui-icon-more, .mui-bar-nav>a ';
	$("a").not(unbind).attr("onclick","return false");
	$("a").not(unbind).on("tap", function (e) {
		e.preventDefault();
		e.stopPropagation();
		
		if(location.href.indexOf($(this).attr("href").split("?")[0])==-1){
		
		try{mui.trigger($(".mui-backdrop")[0],'tap');}catch(e){}
		router.href($(this).attr("href"));
		}
		
		return false;
	})
	//页面底部的跳转
	$(".mui-tab-item").off("tap");
	mui(".mui-bar-tab").on('tap','a',function(e){
		e.preventDefault();
		e.stopPropagation();
		var locparam = {
				psids:param.psids,
				LOGIN_USER:param.LOGIN_USER,
				USER_PSID:param.USER_PSID,
				psid:param.psid
		};
		param = locparam;
		
		if(location.href.indexOf($(this).attr("href").split("?")[0])==-1){
			try{mui.trigger($(".mui-backdrop")[0],'tap');}catch(e){}
			router.href($(this).attr("href"));
		}
		//try{if(closeSingleWebViews)closeSingleWebViews();}catch(e){}
		return false;
		
	});
	//页面顶部的首页跳转
	mui('.mui-scroll-wrapper').on('tap','a',function(e){
		e.preventDefault();
		e.stopPropagation();
		if($(this).attr("href")=="index.html"){
			var locparam = {
					psids:param.psids,
					LOGIN_USER:param.LOGIN_USER,
					USER_PSID:param.USER_PSID,
					psid:param.psid
			};
			param = locparam; 
		}
		
		try{mui.trigger($(".mui-backdrop")[0],'tap');}catch(e){}
		router.href($(this).attr("href"));
		//try{if(closeSingleWebViews)closeSingleWebViews();}catch(e){}
		return false;
	});
	}catch(e){
	}
}
function noticeRef(){
	var notpages = ['index','monitor','work','myInfor','notice'];
	$.each(notpages, function() {
		try{
			var detailPage = plus.webview.getWebviewById(this);
			if(detailPage)mui.fire(detailPage,'refresh',param);
		}catch(e){}
	});
}
function Toindites(){
	var oldhref = [];
	oldhref[0] = $("#monthport").attr("href");
	oldhref[1] = $("#yearport").attr("href");
	oldhref[2] = $("#yichangeq").attr("href");
	oldhref[3] = $("#quexianeq").attr("href");
	oldhref[4] = $("#xunshieq").attr("href");
	oldhref[5] = $("#qxdmu").attr("href");
	oldhref[6] = $("#xsdjmu").attr("href");
	this.refOther = function(){
		var haveto = ["index","monitor","work","myInfor"];
    	var launch = plus.webview.currentWebview()
		var detailPage = plus.webview.all();
		$.each(detailPage,function(){
			if($.inArray(this.id,haveto)&&launch.id!=this.id){
				mui.fire(this,'refresh',param);
			}
		})
	}
	this.dealHref = function(){
		if(param.psids.split(",").length==1){
			try{
				param.psid=param.psids.split(",")[0];
				$("#monthport").attr("href","./reportGL.html?datesel=month");
				$("#yearport").attr("href","./reportGL.html?datesel=year");
				$("#yichangeq").attr("href","./deviceGJ.html");
			
				$("#quexianeq").attr("href") && $("#quexianeq").attr("href","./defectQXD.html?"+$("#quexianeq").attr("href").split("?")[1]);
			
				$("#xunshieq").attr("href")&& $("#xunshieq").attr("href","./patrolDJ.html?"+$("#xunshieq").attr("href").split("?")[1]);
				$("#qxdmu").attr("href") && $("#qxdmu").attr("href","./defectQXD.html?"+$("#qxdmu").attr("href").split("?")[1]);
				$("#xsdjmu").attr("href") && $("#xsdjmu").attr("href","./patrolDJ.html?"+$("#xsdjmu").attr("href").split("?")[1]);
			}catch(e){
			}
			
		}else{
			delete param.psid;
			$("#monthport").attr("href",oldhref[0]);
			$("#yearport").attr("href",oldhref[1]);
			$("#yichangeq").attr("href",oldhref[2]);
			$("#quexianeq").attr("href",oldhref[3]);
			$("#xunshieq").attr("href",oldhref[4]);
			$("#qxdmu").attr("href",oldhref[5]);
			$("#xsdjmu").attr("href",oldhref[6]);
		}
		/*var launch = plus.webview.currentWebview()
		var detailPage = plus.webview.all();
		$.each(detailPage,function(){
			if($.inArray(this.id,haveto)&&launch.id!=this.id){
				mui.fire(this,'refresh',param);
			}
		})*/
		
	}
}